package com.vercon.moensmart.utils;

import android.os.Handler;

import androidx.annotation.Nullable;

import com.vercon.common.Constants;
import com.vercon.common.utils.LogUtils;
import com.vercon.common.utils.MirrorDataStorage;
import com.vercon.moensmart.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class WebsocketMoen {

    private final String TAG = WebsocketMoen.class.getSimpleName();

    private volatile WebSocket mWebSocket;
    private final int connect_success = 1,connect_error = -1,connect_reset = 2;
    private int connect_state = connect_error;
    private OkHttpClient mClient;
    private boolean isReceivePong;
    private Handler mHandler;

    /**
     * WS初始化
     * */
    public void WSinit() {
        mHandler = new Handler();
        //连接前等待动画
        mClient = new OkHttpClient.Builder()
                .readTimeout(3, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(3, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(3, TimeUnit.SECONDS)//设置连接超时时间
                .pingInterval(10, TimeUnit.SECONDS)//设置心跳
                .build();
        WSConnect();

    }

    /**
     * WS连接
     * */
    public synchronized void WSConnect() {
        cancel();
        //关闭心跳发送，避免心跳重复
        String url;
        if (BuildConfig.DEBUG) {
            url = "wss://6v0tieni24.execute-api.cn-northwest-1.amazonaws.com.cn/dev/";
        } else {
            url = "wss://guhp87wxe1.execute-api.cn-northwest-1.amazonaws.com.cn/prod/";
        }
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", MirrorDataStorage.instance().getString(Constants.STORAGE_KEY_TOKEN, ""))
                .build();
        mWebSocket = mClient.newWebSocket(request, new WsListener());
        mWebSocket.request();
    }

    public synchronized void resetConnect(){
        cancel();
        if(mWebSocket != null){
            mWebSocket.request();
        }
    }

    /**
     * 回调
     * */
    class WsListener extends WebSocketListener {
        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            //连接关闭...
            LogUtils.e(TAG,"WS连接关闭！"+code+reason);
            connect_state = connect_error;
            String token = MirrorDataStorage.instance().getString(Constants.STORAGE_KEY_TOKEN,"");
            //disconnect(1000,"close");
            if(!token.equals("")){
                if(connect_state == connect_error){
                    connect_state = connect_reset;
                    resetConnect();
                }
            }
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
            //客户端主动关闭时回调
            LogUtils.e(TAG,"主动关闭" + code);
            connect_state = connect_error;
            String token = MirrorDataStorage.instance().getString(Constants.STORAGE_KEY_TOKEN,"");
            if(!token.equals("")){
                WSConnect();
            }
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
            super.onFailure(webSocket, t, response);
            // 出错了
            LogUtils.e(TAG,"WS连接错误！错误信息：" + t.getMessage());
            if(connect_state != connect_reset){
                connect_state = connect_error;
            }
            String token = MirrorDataStorage.instance().getString(Constants.STORAGE_KEY_TOKEN,"");
            if(!token.equals("")){
                if(connect_state == connect_error){
                    connect_state = connect_reset;
                    resetConnect();
                }
            }
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            // 收到服务端发送来的 String 类型消息
            LogUtils.e(TAG,"WS收到消息,text ="+text);
            if(listener != null){
                listener.onMessage(text);
            }
        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);

        }

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            LogUtils.e(TAG,"onOpen ，response ="+response);
            connect_state = connect_success;
        }
    }



    /**
     * WS主动断开连接
     *
     * @param code
     * @param reason
     */
    public void disconnect(int code, String reason) {
        if (mWebSocket != null)
            mWebSocket.close(code, reason);
    }

    public void cancel() {
        if (mWebSocket != null)
            mWebSocket.cancel();
    }

    public void destroy(){
        disconnect(1000,"close");
        listener = null;
    }


    private OnMessageListener listener;
    public void setListener(OnMessageListener listener){
        this.listener = listener;
    }

    public interface OnMessageListener{
        void onMessage(String msg);
    }

}
